#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/7/9 0:43
# @Author : LZQ
# @Version：V 0.1
# @File : menu.py
# @desc :
from app.api_v1 import api
from sqlalchemy import or_, and_
from __init__ import db, redis_store
from app.utils.status_code import RET
from flask import current_app, g, request, jsonify
from app.token_verify import verify
from sqlalchemy.exc import IntegrityError
from app.models import Permission, Permissionapi


@api.route("/menus", methods=['GET'])
@verify
def get_menus():
    try:
        permissions = Permission.query.filter(Permission.ps_level == '0').all()
        data = []
        msg = {"msg": "获取数据成功", "status": 200}
        meta = {"meta": msg}
        for permission in permissions:
            permission_dict = {}
            permission_dict['id'] = permission.ps_id
            permission_dict['authName'] = permission.ps_name
            permission_dict['path'] = Permissionapi.query.filter(
                Permissionapi.ps_id == permission.ps_id).first().ps_api_path
            permission_dict['children'] = []
            leve2_permissions = Permission.query.filter(Permission.ps_pid == permission.ps_id,
                                                        and_(Permission.ps_level == '1')).all()
            for children_permission in leve2_permissions:
                children_permission_dict = {}
                children_permission_dict['id'] = children_permission.ps_id
                children_permission_dict['authName'] = children_permission.ps_name
                children_permission_dict['path'] = Permissionapi.query.filter(
                    Permissionapi.ps_id == children_permission.ps_id).first().ps_api_path
                children_permission_dict['children'] = []
                permission_dict['children'].append(children_permission_dict)
                level3_permissions = Permission.query.filter(Permission.ps_pid == children_permission.ps_id,
                                                             and_(Permission.ps_level == '2')).all()
                for level3_permission in level3_permissions:
                    level3_permission_dict = {}
                    level3_permission_dict['id'] = level3_permission.ps_id
                    level3_permission_dict['authName'] = level3_permission.ps_name
                    level3_permission_dict['path'] = Permissionapi.query.filter(
                        Permissionapi.ps_id == level3_permission.ps_id).first().ps_api_path
                    level3_permission_dict['children'] = []
                    children_permission_dict['children'].append(level3_permission_dict)
            data.append(permission_dict)
    except Exception as e:
        current_app.logger(e)
        msg = {"msg": "获取数据失败", "status": 500}
        meta = {"meta": msg}
        data = {}
        return jsonify({'data': data, 'meta': meta})
    return jsonify({"data": data, 'meta': meta})
